<template>
  <!-- 存储记录 -->
  <section class="content-section">
    <div class="section-header">
      <h2>存储记录控制面板（用于调试，所有的数据都存储在这里展示）</h2>
      <p>查看插件在Chrome存储中的所有数据</p>
    </div>
    
    <div class="storage-manager">
      <div class="storage-actions">
        <el-button type="primary" @click="refreshStorage">刷新数据</el-button>
        <el-button @click="clearAllStorage">清空所有存储</el-button>
      </div>
      
      <div class="storage-list">
        <div class="list-header">
          <h3>Chrome Storage 数据</h3>
          <div class="storage-stats">
            <span>存储项数量: {{ Object.keys(storageData).length }}</span>
          </div>
        </div>
        
        <div class="storage-items-container">
          <div v-for="(value, key) in storageData" :key="key" class="storage-item">
            <div class="storage-header">
              <h4>{{ key }}</h4>
              <div class="storage-actions">
                <el-button size="mini" @click="copyStorage(key)">复制</el-button>
                <el-button size="mini" @click="downloadStorage(key)">下载</el-button>
                <el-button size="mini" type="danger" @click="deleteStorage(key)">删除</el-button>
              </div>
            </div>
            <div class="storage-content" >
              <pre style="max-width: 666px; overflow: auto;">{{ JSON.stringify(value, null, 2) }}</pre>
            </div>
          </div>
        </div>
      </div>
    </div>
  </section>
</template>

<script>
import { getStorage, setStorage, removeStorage } from '../../../utils/chrome'

export default {
  name: 'StoragePage',
  data() {
    return {
      storageData: {}
    }
  },
  async mounted() {
    await this.loadStorageData()
  },
  methods: {
    /**
     * 加载存储数据
     * 从各个数据源收集数据并组合成存储数据对象
     */
    async loadStorageData() {
      // 从Chrome存储API获取数据
      this.storageData = {
        settings: await this.getSettingsFromParent(),
        whitelist: await this.getWhitelistFromParent(),
        mockList: await this.getMockListFromParent(),
        requestList: await this.getRequestListFromParent(),
      }
    },

    /**
     * 刷新存储数据
     * 重新加载所有存储数据并显示成功消息
     */
    async refreshStorage() {
      await this.loadStorageData()
      this.$message.success('存储数据刷新成功')
    },

    /**
     * 清空所有存储数据
     * 显示确认对话框后清空所有存储数据
     */
    clearAllStorage() {
      this.$confirm('确定要清空所有存储数据吗？', '确认', {
        type: 'warning'
      }).then(() => {
        this.storageData = {}
        this.$message.success('存储数据清空成功')
      })
    },

    /**
     * 复制存储数据到剪贴板
     * @param {string} key - 存储项的键名
     */
    copyStorage(key) {
      const data = JSON.stringify(this.storageData[key], null, 2)
      navigator.clipboard.writeText(data).then(() => {
        this.$message.success('数据已复制到剪贴板')
      })
    },

    /**
     * 下载存储数据为JSON文件
     * @param {string} key - 存储项的键名
     */
    downloadStorage(key) {
      const data = JSON.stringify(this.storageData[key], null, 2)
      const blob = new Blob([data], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `${key}.json`
      a.click()
      URL.revokeObjectURL(url)
    },

    /**
     * 删除指定的存储项
     * @param {string} key - 要删除的存储项键名
     */
    deleteStorage(key) {
      var self=this
      this.$confirm(`确定要删除存储项 "${key}" 吗？`, '确认', {
        type: 'warning'
      }).then(async () => {
        try {
          // 从本地数据中删除
          delete this.storageData[key]
          
          // 从Chrome存储中删除
          await removeStorage(key)

          self.loadStorageData()
          
          this.$message.success('存储项删除成功')
        } catch (error) {
          console.error('删除存储项失败:', error)
          this.$message.error('删除存储项失败: ' + error.message)
        }
      })
    },

    // 以下方法用于从Chrome存储获取数据
    async getSettingsFromParent() {
      const saved = await getStorage('interceptor-settings')
      return saved ? saved['interceptor-settings'] : {}
    },

    async getWhitelistFromParent() {
      const saved = await getStorage('whitelist')
      return saved ? saved.whitelist : []
    },

    async getMockListFromParent() {
      const saved = await getStorage('mockList')
      console.log("🚀 ~ getMockListFromParent ~ mockList saved:", saved)
      return saved ? saved['mockList'] : []
    },

    async getRequestListFromParent() {
      const saved = await getStorage('requestList')
      console.log("🚀 ~ getRequestListFromParent ~ requestList  saved:", saved)
      return saved ? saved['requestList'] : []
    }
  }
}
</script>

<style scoped>
/* 存储相关样式 */
.storage-item {
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  margin-bottom: 15px;
}

.storage-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  background-color: #f5f5f5;
  border-bottom: 1px solid #e0e0e0;
}

.storage-content {
  padding: 15px;
  max-height: 300px;
  overflow-y: auto;
}

.storage-content pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.storage-manager {
  margin-top: 20px;
}

.storage-actions {
  margin-bottom: 20px;
}

.storage-list {
  margin-top: 20px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e0e0e0;
}

.storage-stats {
  color: #666;
  font-size: 14px;
}

.storage-items-container {
  max-height: 600px;
  overflow-y: auto;
}
</style>